package com.jinhuhang.u2.invertmodule;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.api.RetrofitUtils;
import com.jinhuhang.u2.common.base.activity.SimpleBaseActivity;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.entity.CreditorRightsDetailEntity;
import com.jinhuhang.u2.entity.ProjectDetail;
import com.jinhuhang.u2.entity.RasierVoucher;
import com.jinhuhang.u2.entity.UserBean;
import com.jinhuhang.u2.invertmodule.adapter.WelfareAdapter;
import com.jinhuhang.u2.myselfmodule.engine.user.UserActivity;
import com.jinhuhang.u2.ui.MainActivity;
import com.jinhuhang.u2.ui.badge.MathUtil;
import com.jinhuhang.u2.ui.customview.CustomToast;
import com.jinhuhang.u2.util.MathUtils;
import com.jinhuhang.u2.util.U2Util;
import com.jinhuhang.u2.util.http.HttpWrapper;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.http.Result;
import com.jinhuhang.u2.util.http.ResultList;
import com.jinhuhang.u2.util.http.T;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by caoxiaowei on 2017/7/6.
 */
public class ProjectBuyActivity extends SimpleBaseActivity  {


    List<CreditorRightsDetailEntity.DataBean> mDataBeen = new ArrayList<CreditorRightsDetailEntity.DataBean>();

    WelfareAdapter mExperienceAdapter;
    boolean show = false;
    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.name_zz)
    TextView mNameZz;
    @Bind(R.id.yelid_zz)
    TextView mYelidZz;
    @Bind(R.id.month_zz)
    TextView mMonthZz;
    @Bind(R.id.type_zz)
    TextView mTypeZz;
    @Bind(R.id.money_zz)
    TextView mMoneyZz;
    @Bind(R.id.surpluses_zz)
    TextView mSurplusesZz;
    @Bind(R.id.img_buy)
    ImageView mImgBuy;
    @Bind(R.id.fulilay)
    LinearLayout mFulilay;
    @Bind(R.id.fulilist)
    ListView mExperiencelist;
    @Bind(R.id.laylist_zz)
    LinearLayout mLaylist;
    @Bind(R.id.zz_money)
    TextView mZzMoney;
    @Bind(R.id.comfirm)
    TextView mComfirm;

    int tenderid;
    String money;
    ProjectDetail mProjectDetail;
    int type;
    @Bind(R.id.addyeild_buy)
    TextView mAddyeildBuy;
    @Bind(R.id.zz_money1)
    TextView mZzMoney1;

    @Nullable
    @OnClick({R.id.fulilay, R.id.back, R.id.comfirm})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.fulilay:
                if (mBorrowBeen.size() == 0) {
                    CustomToast.showToast("没有可用福利！");
                    break;
                }
                if (show) {
                    show = false;
                    mImgBuy.setImageResource(R.drawable.touzi_tiaozhuan);
                    mExperiencelist.setVisibility(View.GONE);
                    mLaylist.setVisibility(View.GONE);
                } else {
                    show = true;
                    mImgBuy.setImageResource(R.drawable.touzi_downbutton_layout);
                    mExperiencelist.setVisibility(View.VISIBLE);
                    mLaylist.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.back:
                finish();
                break;
            case R.id.comfirm:
                checkToken();

                break;
        }
    }

    private void checkToken(){
        addSubscription(RetrofitUtils.getInstance().build()
                .checkToken(MainActivity.userbean.getUserId(),MainActivity.userbean.getToken())
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<String>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<String> o) {
                        if (o.getCode()==200){
                            Map<String,String> map = new HashMap<>();
                            name=MainActivity.userbean.getUserName();
                            pwd=MainActivity.userbean.getLoginPwd();
                            map.put("username",MainActivity.userbean.getUserName());
                            map.put("userId", Constant.DEFAULT_USER_ID);
                            map.put("password",MainActivity.userbean.getLoginPwd());
                            map.put("loginType",Constant.PLATFORM);
                            map.put("token",MainActivity.userbean.getToken());
                            Login(map);
                            MainActivity.checktoken=true;
                        }else {
                            //token 失效
                            MainActivity.checktoken=false;
                            MainActivity.tip=null;
                            if (o.getCode()!=301) {
                                MainActivity.tip=o.getInfo();
                            }
                            if (MainActivity.tip!=null) {
                                CustomToast.showToast(MainActivity.tip);
                            }
                            Intent intent=new Intent(MyApplication.getContext(), UserActivity.class);
                            intent.putExtra("type",UserActivity.LOGIN);
                            startActivity(intent);
                            finish();
                        }
                    }

                }));
    }

    String name,pwd;
    public void Login(Map<String, String> map) {
        //  mView.showDialog("登录中...");
        RetrofitUtils.getInstance().build()
                .login(map)
                .compose(T.D())
                .subscribe(new Result<HttpWrapper<UserBean>>() {
                    @Override
                    protected void onSuccess(HttpWrapper<UserBean> o) {
                        MainActivity.userbean=o.getData();
                        MainActivity.userbean.setUserName(name);
                        MainActivity.userbean.setLoginPwd(pwd);
                        MyApplication.mSpUtil.setUser(MainActivity.userbean);
                        if (MathUtils.subtract(MainActivity.userbean.getUseMoney(),money)>=0) {
                            submit();
                        }else {
                            CustomToast.showToast("余额不足，请充值！");
                        }
                    }

                    @Override
                    protected void onFinish() {
                        //     mView.dissDialog();
                    }
                });
    }
    boolean click=false;
    private long exitTime = 0l;
    private void submit() {


        if (click)return;
        if ((System.currentTimeMillis() - exitTime) > 3000) {
            exitTime = System.currentTimeMillis();
        }else {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("borrowId", String.valueOf(tenderid));
        map.put("investMoney", money);
        if (dikouid!=0) {
            if (Double.parseDouble(money)<mBorrowBeen.get(dikoupos).getLowestAccount()){
                CustomToast.showToast("投资金额低于该抵扣券起投金额");
                return;
            }
            map.put("moneyCouponId", String.valueOf(dikouid));
        }
        if (jiaxiid!=0) {
            if (Double.parseDouble(money)<mBorrowBeen.get(jiapos).getLowestAccount()){
                CustomToast.showToast("投资金额低于该加息券起投金额");
                return;
            }
            map.put("couponId", String.valueOf(jiaxiid));
        }
        showDialog(null);
        map.put("source", "3");
        map.put("userId", MainActivity.uid);
        map.put("redelivery", "0");
        click=true;
        addSubscription(RetrofitUtils.getInstance().build()
                .prodectInvert(map)
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<String>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<String> data) {
                        jump(data.code);
                    }
                    @Override
                    protected void onFaild() {
                        super.onFaild();
                        click=false;
                    }

                    @Override
                    protected void onFinish() {
                        super.onFinish();
                        dissDialog();
                    }
                }));
    }

    private void jump(int code) {
        if (type == 1) {
            if (code == 200) {
                Intent intent = new Intent(this, ResultActivity.class);
                intent.putExtra("type", Constant.project_success);
                intent.putExtra("title", mProjectDetail.getTitle());
                intent.putExtra("apr", mProjectDetail.getRangeApr());
                intent.putExtra("term", mMonthZz.getText().toString()+"");
                intent.putExtra("money", String.valueOf(money));
                if (dikouid!=0){
                    intent.putExtra("dikou", mBorrowBeen.get(dikoupos).getFaceValue());
                    intent.putExtra("money", MathUtils.subtract(money,mBorrowBeen.get(dikoupos).getFaceValue())+"" );
                }
                if (jiaxiid!=0){
                    intent.putExtra("jiaxi", String.valueOf(mBorrowBeen.get(jiapos).getFaceValue()));
                }
                startActivity(intent);
                finish();
            } else {
                Intent intent = new Intent(this, ResultActivity.class);
                intent.putExtra("type", Constant.project_fail);
                startActivity(intent);
            }
        }
        if (type == 2) {
            if (code == 200) {
                Intent intent = new Intent(this, ResultActivity.class);
                intent.putExtra("type", Constant.tender_success);
                intent.putExtra("title", mProjectDetail.getTitle());
                intent.putExtra("apr", mProjectDetail.getApr());
                intent.putExtra("term", mMonthZz.getText().toString()+"");
                intent.putExtra("money", money);
                if (dikouid!=0){
                    intent.putExtra("dikou", mBorrowBeen.get(dikoupos).getFaceValue()+"");
                    intent.putExtra("money", MathUtils.subtract(money,mBorrowBeen.get(dikoupos).getFaceValue())+"" );
                }
                if (jiaxiid!=0){
                    intent.putExtra("jiaxi", mBorrowBeen.get(jiapos).getFaceValue());
                }
                startActivity(intent);
                finish();
            } else {
                Intent intent = new Intent(this, ResultActivity.class);
                intent.putExtra("type", Constant.tender_fail);
                startActivity(intent);
            }
        }
    }

    List<RasierVoucher> mBorrowBeen = new ArrayList<>();

    @Override
    protected void initView() {
        super.initView();
        mProjectDetail = (ProjectDetail) getIntent().getSerializableExtra("mProjectDetail");
        tenderid = getIntent().getIntExtra("bid", 0);
        money = getIntent().getStringExtra("money");
        type = getIntent().getIntExtra("type", 0);
        mTvTitle.setText("确认出借");
        mExperienceAdapter = new WelfareAdapter(mBorrowBeen, this);
        mExperiencelist.setAdapter(mExperienceAdapter);
        if (mProjectDetail != null) {
            if (mProjectDetail.getStyle() == 0) {
                mTypeZz.setText("等额本息");
            } else if (mProjectDetail.getStyle() == 1) {
                mTypeZz.setText("先息后本");
            } else if (mProjectDetail.getStyle() == 2) {
                mTypeZz.setText(" 到期本息");
            }
            if (mProjectDetail.getTimeLimitType()==1){
                mMonthZz.setText(mProjectDetail.getTimeLimit() + "个月");
            }else if (mProjectDetail.getTimeLimitType()==2){
                mMonthZz.setText(mProjectDetail.getTimeLimit() + "年");
            }else if (mProjectDetail.getTimeLimitType()==3){
                mMonthZz.setText(mProjectDetail.getTimeLimit() + "天");
            }
            mNameZz.setText(mProjectDetail.getTitle());
            if (type==1 || type==3) {
                mYelidZz.setText(mProjectDetail.getRangeApr() + "%");
            }else {
                mYelidZz.setText(mProjectDetail.getApr() + "%");
            }
            mMoneyZz.setText(MainActivity.userbean.getUseMoney() + "元");
            mSurplusesZz.setText(money + "元");

            if (type==1 || type==3){
                BigDecimal result1 = U2Util.caculateInterest(mProjectDetail.getStyle(),
                        mProjectDetail.getMinApr(), mProjectDetail.getTimeLimit(),
                        money, String.valueOf(mProjectDetail.getTimeLimitType()));
                result1 = result1.setScale(2, BigDecimal.ROUND_HALF_UP);
                BigDecimal result2 = U2Util.caculateInterest(mProjectDetail.getStyle(),
                        mProjectDetail.getMaxApr(), mProjectDetail.getTimeLimit(),
                        money, String.valueOf(mProjectDetail.getTimeLimitType()));
                result2 = result2.setScale(2, BigDecimal.ROUND_HALF_UP);
                mZzMoney.setText(result1.toString()+"~"+result2.toString());
            }else {
                BigDecimal result2 = U2Util.caculateInterest(mProjectDetail.getStyle(),
                        mProjectDetail.getApr(), mProjectDetail.getTimeLimit(),
                        money, String.valueOf(mProjectDetail.getTimeLimitType()));
                result2 = result2.setScale(2, BigDecimal.ROUND_HALF_UP);
                mZzMoney.setText(result2.toString());
            }

        }


        mExperiencelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                if (mBorrowBeen.get(position).getCouponType() == 1) {
                    if (dikouid == 0) {
                        dikouid = mBorrowBeen.get(position).getId();
                        mBorrowBeen.get(position).setSelect(true);
                        dikoupos = position;
                    } else {
                        if (dikoupos == position) {
                            dikouid = 0;
                            mBorrowBeen.get(position).setSelect(false);
                            dikoupos = 0;
                        } else {
                            mBorrowBeen.get(dikoupos).setSelect(false);
                            mBorrowBeen.get(position).setSelect(true);
                            dikoupos = position;
                        }

                    }
                } else {
                    if (jiaxiid == 0) {
                        getValue(position);
                        jiaxiid = mBorrowBeen.get(position).getId();
                        mBorrowBeen.get(position).setSelect(true);
                        mAddyeildBuy.setVisibility(View.VISIBLE);
                        if (mBorrowBeen.get(position).getInterestKey() == 0) {
                            mAddyeildBuy.setText("+" + mBorrowBeen.get(position).getFaceValue() + "%/" + mBorrowBeen.get(position).getInterestValue() + "天");
                        } else {
                            mAddyeildBuy.setText("+" + mBorrowBeen.get(position).getFaceValue() + "%/按标加息");
                        }

                    } else {
                        if (jiapos == position) {
                            jiaxiid = 0;
                            mBorrowBeen.get(position).setSelect(false);
                            mAddyeildBuy.setVisibility(View.GONE);
                            mZzMoney1.setText("0");
                        } else {
                            getValue(position);
                            mAddyeildBuy.setVisibility(View.VISIBLE);
                            mBorrowBeen.get(jiapos).setSelect(false);
                            mBorrowBeen.get(position).setSelect(true);
                            if (mBorrowBeen.get(position).getInterestKey() == 0) {
                                mAddyeildBuy.setText("+" + mBorrowBeen.get(position).getFaceValue() + "%/" + mBorrowBeen.get(position).getInterestValue() + "天");
                            } else {
                                mAddyeildBuy.setText("+" + mBorrowBeen.get(position).getFaceValue() + "%/按标加息");
                            }
                        }
                    }
                    jiapos = position;
                }
                mExperienceAdapter.notifyDataSetChanged();
            }
        });
    }


    //加息券计算利息
    private void getValue(int pos) {

        int interestValue = mBorrowBeen.get(pos).getInterestValue();
        if (mBorrowBeen.get(pos).getInterestKey()==0){ //天标加息
            if (mProjectDetail.getTimeLimitType()==3){//产品，类型 天
                int tl = mProjectDetail.getTimeLimit();
                BigDecimal result = new BigDecimal(0);
                if (tl > interestValue) {
                    //加息券按天计息 *  年化利率/365   *加息天数
                    result = U2Util.caculateRaiserVoucherInterestByDay(mBorrowBeen.get(pos).getFaceValue(), money, mBorrowBeen.get(pos).getInterestValue());
                } else {
                    result = U2Util.caculateRaiserVoucherInterestByDay(mBorrowBeen.get(pos).getFaceValue(), money, tl);
                }
                result = result.setScale(2, BigDecimal.ROUND_HALF_UP);
                mZzMoney1.setText(result.toString());
            }
            if (mProjectDetail.getTimeLimitType()==1){///产品，类型 月
                Calendar cureentCalendar = Calendar.getInstance();
                Integer timeLimit2 = mProjectDetail.getTimeLimit();
               // Date currentTime = cureentCalendar.getTime();
             //   long currentTimeLong = currentTime.getTime();
                long currentTimeLong = mProjectDetail.getLocalTime();
                cureentCalendar.add(Calendar.MONTH,timeLimit2 );
                Date time = cureentCalendar.getTime();
                long timeLong = time.getTime();
                long  days =( timeLong  -currentTimeLong)/(24 * 60 * 60 * 1000);

                BigDecimal result = new BigDecimal(0);
                if(interestValue>=days){
                    result = U2Util.caculateRaiserVoucherInterestByMonth(mBorrowBeen.get(pos).getFaceValue(),money,mProjectDetail.getTimeLimit());
                }else{
                    result = U2Util.caculateRaiserVoucherInterestByDay(mBorrowBeen.get(pos).getFaceValue(),money,interestValue);
                }
                result=    result.setScale(2,   BigDecimal.ROUND_HALF_UP);
                mZzMoney1.setText(result.toString());
            }
        }else {
            //按标进行计算
            int timeLimitType = mProjectDetail.getTimeLimitType();
            if(timeLimitType==1){
                //月  (本金*利率)/365X(期限/12)
                BigDecimal result = U2Util.caculateRaiserVoucherInterestByMonth(mBorrowBeen.get(pos).getFaceValue(),money,mProjectDetail.getTimeLimit());
                result=    result.setScale(2,    BigDecimal.ROUND_HALF_UP);
                mZzMoney1.setText(result.toString());
            }

            if(timeLimitType==2){
                //年
                BigDecimal result = U2Util.caculateRaiserVoucherInterestByYear(mBorrowBeen.get(pos).getFaceValue(),money,mProjectDetail.getTimeLimit());
                result=    result.setScale(2,  BigDecimal.ROUND_HALF_UP);
                mZzMoney1.setText(result.toString());
            }

            if(timeLimitType==3){
                //天
                BigDecimal result = U2Util.caculateRaiserVoucherInterestByDay(mBorrowBeen.get(pos).getFaceValue(),money,mProjectDetail.getTimeLimit());
                result=    result.setScale(2,    BigDecimal.ROUND_HALF_UP);
                mZzMoney1.setText(result.toString());
            }
        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_project_buy;
    }

    int pageNo = 1;
    int pageSize = 50;

    //可用福利
    @Override
    protected void initData() {
        super.initData();
        jiaxi.clear();
        ;
        dikou.clear();
        mBorrowBeen.clear();
        Map<String, Integer> map = new HashMap<>();
        if (type == 1) {
            map.put("type", 1);
        } else {
            map.put("type", 0);
        }

        map.put("userId", Integer.parseInt(MainActivity.uid));
        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        addSubscription(RetrofitUtils.getInstance().build()
                .welfareLst(map)
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<RasierVoucher>>() {
                    @Override
                    protected void onSuccess(HttpWrapperList<RasierVoucher> data) {

                        for (int po = 0; po < data.getData().size(); po++) {
                            if (data.getData().get(po).getCouponType() == 1) {
                                dikou.add(po + "");
                            } else {
                                jiaxi.add(po + "");
                            }
                        }
                        mBorrowBeen.addAll(data.getData());
                        mExperienceAdapter.notifyDataSetChanged();
                    }
                }));
    }

    //加息券位置
    List<String> jiaxi = new ArrayList<>();
    //抵扣券位置
    List<String> dikou = new ArrayList<>();

    int jiaxiid, dikouid;
    int jiapos, dikoupos;

//    @Override
//    public void setId(boolean add, int pos) {
//        if (add) {
//            if (mBorrowBeen.get(pos).getCouponType() == 1) {
//                dikouid = mBorrowBeen.get(pos).getId();
//            } else {
//                jiaxiid = mBorrowBeen.get(pos).getId();
//            }
//        } else {
//            if (mBorrowBeen.get(pos).getCouponType() == 1) {
//                dikouid = 0;
//            } else {
//                jiaxiid = 0;
//            }
//        }
//    }

}
